/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package testing;

import cfar.actors.Node;
import cfar.actors.distributed.ActorServer;
import cfar.ff.data.Assocs.Assoc2;
import cfar.ff.data.List;
import cfar.ff.fun.F1;
import cfar.ff.fun.Seq;
import cfar.ff.interfaces.Sequence;
import cfar.utils.IO;
import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.Random;
import java.lang.Math;
/**
 *
 * @author haoyun
 */
public class genTraj {

    public static List<Double> genTrajec(Double iniX){
        List<Double> trajX=List.list(iniX);
        int timestep=1000;
        double vn=0;
        double xn=iniX;
        double vhalf;
        double gamma=6.4114;
        double deltat=0.14;
        double delta=Math.sqrt((2*0.616*gamma)/(deltat/2));
        Random rand=new Random();
        double R=rand.nextGaussian()*delta;
        for(int i=1;i<timestep;i++){
            vhalf=vn+(deltat/2)*(-xn-gamma*vn+R);
            xn=xn+deltat*vhalf;
            R=rand.nextGaussian()*delta;
            vn=vhalf+deltat/2*(-xn-gamma*vn+R);
            trajX=trajX.snoc(xn);
        }
        return trajX;
    }


    public static F1<Double,java.util.List> work = new F1<Double,java.util.List>() {

        public java.util.List f(Double a) {
            List l=genTraj.genTrajec(a);
            return new java.util.LinkedList(l.getList().toCollection());
        }
    };

    public static F1<Assoc2<InetAddress, Integer>, Node> mknode = new F1<Assoc2<InetAddress, Integer>, Node>() {

        public Node f(Assoc2<InetAddress, Integer> a) {
            try {
                return new Node(a.$1, a.$2);
            } catch (IOException ex) {
                Logger.getLogger(genTraj.class.getName()).log(Level.SEVERE, null, ex);
            }
            return null;
        }
    };


    public static String syncdir = "/tmp/cfar.sync",
                         suffix = "cfs";

    public static void main (String[] arg)throws IOException {
        new File(syncdir).mkdir();

        for (int i = 0; i < 10; i++) {
            new Thread(new ActorServer(syncdir, suffix)).start();
        }

        List<Node> nodes = (List<Node>) Seq.parMap(mknode, IO.available_hosts(syncdir, suffix));
        List<Double> seq=List.list(0.0,1.0,2.0,3.0,4.0,5.0,6.0,7.0,8.0,9.0,10.0);

        Sequence seq2 = Seq.distMap(nodes, work, seq);

//        List<Double> exp = List.list(11.1,12,13,14,15,16,17,18,19,20);

        for (Node n : nodes) {
            n.tell(cfar.actors.Message.stop);
        }

        System.out.println(seq2.head());
        System.exit(0);

    }

}